import React, {useEffect, useRef} from 'react';
import {App, Button, Form, Space, Spin} from "antd";
import {AsyncThunk} from "@reduxjs/toolkit";
import {AsyncThunkConfig} from "@reduxjs/toolkit/src/createAsyncThunk";
import {useAppDispatch} from "../../redux/hook";
import LogFactory from "../../log/LogFactory";
import {FormInstance} from "antd/lib";
import {useNavigate} from "react-router-dom";
import {requestGet} from "../../util/request";
import {compareObject} from "../../util/compare";

interface FormEnhanceUpdateProps<T> {
    /**
     * 添加数据的redux异步action
     */
    fetchData: AsyncThunk<number,any, AsyncThunkConfig> ,
    /**
     * 表单数据的初始值
     */
    initialValues?: Partial<T> ,
    /**
     * 表单的子组件
     */
    children?: React.ReactNode,
    /**
     * 表单的实例
     */
    form?: FormInstance<T>,
    /**
     * 提交按钮的文本
     */
    submitText?: string,

    dataUrl: string ,
    /**
     * 更新数据的id
     */
    updateId : number | string |undefined ,
}

const log = LogFactory.getLog("FormEnhance") ;

const FormEnhanceUpdate = <T,> (props: FormEnhanceUpdateProps<T>) => {

    const { form } = props ;
    const [loading, setLoading] = React.useState<boolean>(true) ;
    // const [form] = Form.useForm<T>() ;
    const { message } = App.useApp() ;
    const dispatch = useAppDispatch() ;
    const navigate = useNavigate() ;
    const dataRef = useRef<T>() ;


    useEffect(() => {
        requestGet<T>(props.dataUrl)
            .then(res => {
                // log.debug("菜单更新",res.data) ;
                dataRef.current = res.data ;
                form?.setFieldsValue(res.data as object ) ;
                setLoading(false);
            }) ;
    },[]) ;

    const onFinish = async (value: T) => {
        log.debug("表单提交的数据: " , value) ;

        let compRes = compareObject(dataRef.current, value) ;
        if (compRes == null){
            message.info("数据没有变化") ;
            return ;
        }
        compRes.id = props.updateId ;
        setLoading(true) ;
        const res = await dispatch(props.fetchData(compRes)).unwrap().then(res => res) ;
        setLoading(false) ;
        if (res > 0){
            message.success("更新数据成功") ;
            navigate("../") ;
        }else {
            message.info("更新数据失败") ;
        }
    } ;

    const onReset = () => {
        form?.resetFields() ;
    };

    return (
        <Spin
            spinning={loading}
            // tip={"正在提交数据..."}
            delay={500}
        >
            <Form<T>
                layout={"horizontal"}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 12 }}
                form={form}
                initialValues={props.initialValues}
                onFinish={onFinish}
            >

                {props.children}
                <Form.Item wrapperCol={{offset: 8,span: 16}}>
                    <Space size={10}>
                        <Button type="primary" htmlType="submit">{props.submitText || "提交" }</Button>
                        <Button type="default" htmlType="reset" onReset={onReset}>重置</Button>
                    </Space>
                </Form.Item>
            </Form>
        </Spin>
    );
};

export default FormEnhanceUpdate;